<template>

  <splitpanes :horizontal="appStore2.device === 'mobile'" class="default-theme">
    <!--左边数据-->
    <pane size="16" class="min-height">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
<!--          <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['scm:scmSupplierOrders:add']">新增</el-button>-->
        </el-col>
        <right-toolbar :search="false" v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="scmSupplierOrdersList"  lazy highlight-current-row @current-change="handleCurrentOrder" >
        <el-table-column label="订单编号" align="left" prop="orderCode" />
        <el-table-column label="" align="center" class-name="small-padding fixed-width" width="20">
          <template #default="scope">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['scm:scmSupplierOrders:remove']"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </pane>
    <pane size="84" style="height: 100%;">
<!--      <el-tabs type="border-card" style="height: 75vh;" >-->
      <el-tabs type="border-card" >
        <el-tab-pane label="订单基础信息" >
          <el-card v-if=!open >
            <h4>提示</h4>
            <ul>
              <li>若添加订单，请先点击 新增 按钮。</li>
              <li>若查看订单，请先点击 订单列表 中订单编号进行查看。</li>
            </ul>
            <el-divider />
          </el-card>

          <el-form ref="scmSupplierOrdersRef" :model="form" :rules="rules" label-width="80px" v-if=open :disabled="orderFormDisabled">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="订单编号" prop="orderCode">
                  <el-input v-model="form.orderCode" placeholder="请输入订单编号" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="订单日期" prop="orderDate">
                  <el-date-picker clearable v-model="form.orderDate" type="date"value-format="YYYY-MM-DD"placeholder="请选择订单日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="订单到货日" prop="requestedDeliveryDate" label-width="90px" >
                  <el-date-picker clearable v-model="form.requestedDeliveryDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择订单到货日">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="到货日回复" prop="repliedDeliveryDate" label-width="90px">
                  <el-date-picker clearable v-model="form.repliedDeliveryDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择到货日回复">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="订单状态" prop="paymentStatus">
                  <el-select v-model="form.paymentStatus" placeholder="请选择订单状态">
                    <el-option v-for="dict in scm_payment_status" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="订单金额" prop="totalAmount">
                  <el-input-number v-model="form.totalAmount" placeholder="订单金额" type="number" :min="0" :controls="false" class="number-right" style="width: 100%;" :precision="2" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="已支付金额" prop="payedAmount" label-width="90px" >
                  <el-input-number v-model="form.payedAmount" placeholder="已支付金额金额" type="number" :min="0" :controls="false" class="number-right" style="width: 100%;" :precision="2" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="发票金额" prop="invoiceAmount" label-width="90px" >
                  <el-input-number v-model="form.invoiceAmount" placeholder="已支付金额金额" type="number" :min="0" :controls="false" class="number-right" style="width: 100%;" :precision="2" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider class="custom-divider">甲方</el-divider>
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="甲方抬头" prop="buyerTitle">
                  <el-input v-model="form.buyerTitle" placeholder="请输入甲方抬头" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="甲方地址" prop="buyerAddress">
                  <el-input v-model="form.buyerAddress" placeholder="请输入甲方地址" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="签署日期" prop="buyerSignDate">
                  <el-date-picker clearable v-model="form.buyerSignDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择甲方签署日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="开户银行" prop="buyerAccountBank">
                  <el-input v-model="form.buyerAccountBank" placeholder="请输入甲方开户银行" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="银行账号" prop="buyerAccountNumber">
                  <el-input v-model="form.buyerAccountNumber" placeholder="请输入甲方银行账号" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系人" prop="buyerPerson">
                  <el-input v-model="form.buyerPerson" placeholder="请输入甲方联系人" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话" prop="buyerPhone">
                  <el-input v-model="form.buyerPhone" placeholder="请输入甲方电话" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>

            </el-row>
            <el-divider class="custom-divider">乙方</el-divider>
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="乙方抬头" prop="sellerTitle">
                  <el-input v-model="form.sellerTitle" placeholder="请输入乙方抬头" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="乙方地址" prop="sellerAddress">
                  <el-input v-model="form.sellerAddress" placeholder="请输入乙方地址" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="签署日期" prop="sellerSignDate">
                  <el-date-picker clearable v-model="form.sellerSignDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择乙方签署日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="开户银行" prop="sellerAccountBank">
                  <el-input v-model="form.sellerAccountBank" placeholder="请输入乙方开户银行" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="银行账号" prop="sellerAccountNumber">
                  <el-input v-model="form.sellerAccountNumber" placeholder="请输入乙方银行账号" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系人" prop="sellerPerson">
                  <el-input v-model="form.sellerPerson" placeholder="请输入乙方联系人" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话" prop="sellerPhone">
                  <el-input v-model="form.sellerPhone" placeholder="请输入乙方电话" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-form ref="scmSupplierOrdersRef2" :model="form" :rules="rules" label-width="80px" v-if=open >
            <el-divider content-position="center" class="custom-divider">合同信息</el-divider>
            <el-row :gutter="24">
<!--              <el-col :span="8">-->
<!--                <el-form-item label="合同名字" prop="contractFileName">-->
<!--                  <el-input v-model="form.contractFileName" placeholder="请输入合同文件名字" />-->
<!--                </el-form-item>-->
<!--              </el-col>-->
              <el-col :span="12">
                <el-form-item label="合同文件" prop="contractFile">
<!--                  <file-upload v-model="form.contractFile"/>-->
                  <div style="display: flex; gap: 10px; align-items: center; width: 100%">
                    <el-input :value="form.contractFile ? form.contractFile.substring(form.contractFile.lastIndexOf('/') + 1) : '' " placeholder="请上传图纸" style="flex: 2;" disabled />
                    <file-upload v-model="form.contractFile" :isShowTip="false" v-if="!orderFormDisabled" />
                    <el-button size="default" type="text" @click="$download.resource(form.contractFile,false)" :disabled="false" native-type="button" formnovalidate>下载</el-button>
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" prop="remarks">
                  <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" :disabled="orderFormDisabled" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div v-if=open style="display: flex; justify-content: space-between; margin-top: 1px;">
            <div>
              <el-button v-if="orderFormDisabled && form.id" type="primary" @click="handleEdit">编 辑</el-button>
            </div>
            <div>
              <el-button v-if="!orderFormDisabled" type="primary" @click="submitForm">保 存</el-button>
              <el-button v-if="!orderFormDisabled" @click="cancel">取 消</el-button>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="订单产品">
          <el-card v-if=!open >
            <h4>提示</h4>
            <ul>
              <li>若添加订单，请先点击 新增 按钮。</li>
              <li>若查看订单，请先点击 订单列表 中订单编号进行查看。</li>
            </ul>
            <el-divider />
          </el-card>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5" v-if="orderFormDisabled && form.id">
              <el-button type="primary" icon="Edit" @click="handleEdit">编 辑</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-if="!orderFormDisabled" type="danger" icon="Delete" @click="handleDeleteScmSupplierOrderItems">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-if="!orderFormDisabled" type="primary" @click="submitForm">保 存</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button v-if="!orderFormDisabled" @click="cancel">取 消</el-button>
            </el-col>
            <right-toolbar v-if="!orderFormDisabled" v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"
                           :search="false" :linked-id="form.id" :attachment-type="21" :attachment-path="form.orderCode"></right-toolbar>
          </el-row>
          <el-form ref="scmSupplierOrdersRef" :model="form" :rules="rules" label-width="80px" v-if=open :disabled="orderFormDisabled">
<!--            <el-row :gutter="10" class="mb8">-->

<!--              <el-col :span="1.5">-->
<!--                <el-button type="primary" icon="Plus" @click="handleAddScmSupplierOrderItems">添加</el-button>-->
<!--              </el-col>-->
<!--              <el-col :span="1.5">-->
<!--                <el-button type="danger" icon="Delete" @click="handleDeleteScmSupplierOrderItems">删除</el-button>-->
<!--              </el-col>-->
<!--            </el-row>-->
            <el-table :data="scmSupplierOrderItemsList" :row-class-name="rowScmSupplierOrderItemsIndex" @selection-change="handleScmSupplierOrderItemsSelectionChange" ref="scmSupplierOrderItems" lazy :scrollbar-always-on="true">
              <el-table-column type="selection" width="50" align="center" />
              <el-table-column label="序号" align="center" prop="index" width="50" fixed/>
<!--              <el-table-column label="产品ID" prop="productId" width="150">-->
<!--                <template #default="scope">-->
<!--                  <el-input v-model="scope.row.productId" placeholder="请输入产品ID" />-->
<!--                </template>-->
<!--              </el-table-column>-->
              <el-table-column label="图号" align="center" prop="scmProjectProducts.drawingNumber" fixed width="98"/>
              <el-table-column label="版本" align="center" prop="scmProjectProducts.version" fixed  />
              <el-table-column label="内版本" align="center" prop="scmProjectProducts.internalVersion" fixed />
              <el-table-column label="品名" align="center" prop="scmProjectProducts.productName" fixed  />
              <el-table-column label="材质" align="center" prop="scmProjectProducts.material"  />
              <el-table-column label="阻燃等级" align="center" prop="scmProjectProducts.inflamingRetardingLevel"  />
              <el-table-column label="规格" align="center" prop="scmProjectProducts.specification" />
              <el-table-column label="型号" align="center" prop="scmProjectProducts.model"  />
              <el-table-column label="颜色" align="center" prop="scmProjectProducts.color"  />
              <el-table-column label="采购类型" prop="purchaseCategory" width="150">
                <template #default="scope">
                  <el-select v-model="scope.row.purchaseCategory" placeholder="请选择采购类型">
                    <el-option v-for="dict in scm_purchase_category" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="部品类型" prop="demandType" width="150">
                <template #default="scope">
                  <el-select v-model="scope.row.demandType" placeholder="请选择部品类型">
                    <el-option v-for="dict in scm_demand_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="机种" prop="model" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.model" placeholder="请输入机种" />
                </template>
              </el-table-column>
<!--              <el-table-column label="出厂编号" prop="manufactureNumber" width="150">-->
<!--                <template #default="scope">-->
<!--                  <el-input v-model="scope.row.manufactureNumber" placeholder="请输入出厂编号" />-->
<!--                </template>-->
<!--              </el-table-column>-->
<!--              <el-table-column label="出厂子编号" prop="manufactureSubNumber" width="150">-->
<!--                <template #default="scope">-->
<!--                  <el-input v-model="scope.row.manufactureSubNumber" placeholder="请输入出厂子编号" />-->
<!--                </template>-->
<!--              </el-table-column>-->
<!--              <el-table-column label="图号、型号" prop="drawingNumberModel" width="150">-->
<!--                <template #default="scope">-->
<!--                  <el-input v-model="scope.row.drawingNumberModel" placeholder="请输入图号、型号" />-->
<!--                </template>-->
<!--              </el-table-column>-->
<!--              <el-table-column label="版本" prop="drawingVersion" width="150">-->
<!--                <template #default="scope">-->
<!--                  <el-input v-model="scope.row.drawingVersion" placeholder="请输入版本" />-->
<!--                </template>-->
<!--              </el-table-column>-->
<!--              <el-table-column label="品名" prop="productName" width="150">-->
<!--                <template #default="scope">-->
<!--                  <el-input v-model="scope.row.productName" placeholder="请输入品名" />-->
<!--                </template>-->
<!--              </el-table-column>-->
<!--              <el-table-column label="材质" prop="material" width="150">-->
<!--                <template #default="scope">-->
<!--                  <el-input v-model="scope.row.material" placeholder="请输入材质" />-->
<!--                </template>-->
<!--              </el-table-column>-->
<!--              <el-table-column label="尺寸" prop="size" width="150">-->
<!--                <template #default="scope">-->
<!--                  <el-input v-model="scope.row.size" placeholder="请输入尺寸" />-->
<!--                </template>-->
<!--              </el-table-column>-->
<!--              <el-table-column label="规格" prop="specification" width="150">-->
<!--                <template #default="scope">-->
<!--                  <el-input v-model="scope.row.specification" placeholder="请输入规格" />-->
<!--                </template>-->
<!--              </el-table-column>-->
<!--              <el-table-column label="颜色" prop="color" width="150">-->
<!--                <template #default="scope">-->
<!--                  <el-input v-model="scope.row.color" placeholder="请输入颜色" />-->
<!--                </template>-->
<!--              </el-table-column>-->
              <el-table-column label="单价类型" prop="unitPriceType" width="150">
                <template #default="scope">
                  <el-select v-model="scope.row.unitPriceType" placeholder="请选择单价类型">
                    <el-option v-for="dict in scm_purchase_category" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="数量" align="center" prop="quantity" width="150">
                <template #default="scope">
                  <el-input-number v-model="scope.row.quantity" placeholder="请输入数量" :min="0" :controls="false" style="width: 100%;"
                                   @change="(value) => handleQuantityChange(value, scope.row)" />
                </template>
              </el-table-column>
              <el-table-column label="单价" align="center" prop="unitPrice" width="150">
                <template #default="scope">
                  <span style="margin-right: 4px;">¥</span>
                  <el-input-number v-model="scope.row.unitPrice" placeholder="请输入单价" :min="0" style="width: 90%;" :controls="false" class="number-right" :precision="2"
                                   @change="(value) => handleUnitPriceChange(value, scope.row)"/>
                </template>
              </el-table-column>
              <el-table-column label="金额" align="center" prop="amount" width="150">
                <template #default="scope">
                  <span style="margin-right: 4px;">¥</span>
                  <el-input-number v-model="scope.row.amount" placeholder="请输入金额" :min="0" style="width: 90%;" :controls="false" class="number-right" :precision="2" />
                </template>
              </el-table-column>
              <el-table-column label="模具费" align="center" prop="moldCost" width="150">
                <template #default="scope">
                  <span style="margin-right: 4px;">¥</span>
                  <el-input-number v-model="scope.row.moldCost" placeholder="请输入模具费" :min="0" style="width: 90%;" :controls="false" class="number-right" :precision="2" />
                </template>
              </el-table-column>
              <el-table-column label="工装费" align="center" prop="jigCost" width="150">
                <template #default="scope">
                  <span style="margin-right: 4px;">¥</span>
                  <el-input-number v-model="scope.row.jigCost" placeholder="请输入工装费" :min="0" style="width: 90%;" :controls="false" class="number-right" :precision="2" />
                </template>
              </el-table-column>
              <el-table-column label="币种" align="center" prop="supplierCurrency" width="150">
                <template #default="scope">
                  <el-select v-model="scope.row.supplierCurrency" placeholder="请选择客户币种">
                    <el-option
                        v-for="dict in scm_currency"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="汇率" align="center" prop="supplierCurrencyRate" width="150">
                <template #default="scope">
                  <el-input-number v-model="scope.row.supplierCurrencyRate" placeholder="请输入客户币种汇率" :min="0" style="width: 90%;" :controls="false" class="number-right" :precision="4" />
                </template>
              </el-table-column>
              <el-table-column label="订单到货日" align="center" prop="requestedDeliveryDate" width="240">
                <template #default="scope">
                  <el-date-picker clearable
                                  v-model="scope.row.requestedDeliveryDate"
                                  type="date"
                                  value-format="YYYY-MM-DD"
                                  placeholder="请选择订单到货日"
                                  style="width: 100%;">
                  </el-date-picker>
                </template>
              </el-table-column>
              <el-table-column label="到货日回复" align="center" prop="repliedDeliveryDate" width="240">
                <template #default="scope">
                  <el-date-picker clearable
                                  v-model="scope.row.repliedDeliveryDate"
                                  type="date"
                                  value-format="YYYY-MM-DD"
                                  placeholder="请选择到货日回复"
                                  style="width: 100%;">
                  </el-date-picker>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </pane>
  </splitpanes>

</template>

<script setup>
import {Pane, Splitpanes} from "splitpanes";
import "splitpanes/dist/splitpanes.css"
const appStore2 = useAppStore()

const props = defineProps({
  projectId: {
    type: String,
    default: ''
  }
})

// const data = reactive({
//   form: {},
//   queryParams: {
//     projectId: props.projectId,
//   }
// });

import { listScmSupplierOrders, getScmSupplierOrders, delScmSupplierOrders, addScmSupplierOrders, updateScmSupplierOrders } from "@/api/scm/scmSupplierOrders";
import useAppStore from "@/store/modules/app.js";

const { proxy } = getCurrentInstance();
const { scm_payment_status } = proxy.useDict('scm_payment_status');
const {
  scm_demand_type,
  scm_project_customer_status,
  scm_product_status,
  scm_project_supplier_status,
  scm_purchase_category,
  scm_currency
} = proxy.useDict(
    "scm_demand_type",
    "scm_project_customer_status",
    "scm_product_status",
    "scm_project_supplier_status",
    "scm_purchase_category",
    "scm_currency"
);

const scmSupplierOrdersList = ref([]);
const scmSupplierOrderItemsList = ref([]);
const open = ref(false);
const orderFormDisabled = ref(true);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedScmSupplierOrderItems = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: props.projectId,
    orderCode: null,
    orderDate: null,
    requestedDeliveryDate: null,
    repliedDeliveryDate: null,
    totalAmount: null,
    receivedAmount: null,
    paymentStatus: null,
    buyerTitle: null,
    buyerAddress: null,
    buyerPerson: null,
    buyerPhone: null,
    buyerAccountBank: null,
    buyerAccountNumber: null,
    buyerSignDate: null,
    sellerTitle: null,
    sellerAddress: null,
    sellerPerson: null,
    sellerPhone: null,
    sellerAccountBank: null,
    sellerAccountNumber: null,
    sellerSignDate: null,
    contractFileName: null,
    contractFile: null,
    remarks: null,
  },
  rules: {
    projectId: [
      { required: true, message: "项目ID不能为空", trigger: "blur" }
    ],
    orderCode: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

// const localProjectId = ref(props.projectId);
// 监听 projectId 变化
watch(
    () => props.projectId,
    (newVal) => {
      console.log('projectId changed to:', newVal);
      queryParams.value.projectId = newVal; // 更新本地变量
      getList();
    }
);

/** 查询供应商订单列表 */
function getList() {
  loading.value = true;
  reset();
  listScmSupplierOrders(queryParams.value).then(response => {
    scmSupplierOrdersList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 添加编辑按钮处理方法
function handleEdit() {
  orderFormDisabled.value = false;
}
// 取消按钮
function cancel() {
  // open.value = false;
  // reset();
  orderFormDisabled.value = true; // 恢复表单禁用状态
  inquiryCurrentOrder(form.value.id);
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    projectId: queryParams.value.projectId,
    orderCode: null,
    orderDate: null,
    requestedDeliveryDate: null,
    repliedDeliveryDate: null,
    totalAmount: null,
    receivedAmount: null,
    paymentStatus: null,
    buyerTitle: null,
    buyerAddress: null,
    buyerPerson: null,
    buyerPhone: null,
    buyerAccountBank: null,
    buyerAccountNumber: null,
    buyerSignDate: null,
    sellerTitle: null,
    sellerAddress: null,
    sellerPerson: null,
    sellerPhone: null,
    sellerAccountBank: null,
    sellerAccountNumber: null,
    sellerSignDate: null,
    contractFileName: null,
    contractFile: null,
    remarks: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  scmSupplierOrderItemsList.value = [];
  proxy.resetForm("scmSupplierOrdersRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加供应商订单";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getScmSupplierOrders(_id).then(response => {
    form.value = response.data;
    scmSupplierOrderItemsList.value = response.data.scmSupplierOrderItemsList;
    open.value = true;
    title.value = "修改供应商订单";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["scmSupplierOrdersRef"].validate(valid => {
    if (valid) {
      form.value.scmSupplierOrderItemsList = scmSupplierOrderItemsList.value;
      form.value.contractFileName = form.value.contractFile ? form.value.contractFile.substring(form.value.contractFile.lastIndexOf('/') + 1) : '';
      if (form.value.id != null) {
        updateScmSupplierOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = true;
          orderFormDisabled.value = true; // 提交成功后恢复表单禁
          inquiryCurrentOrder(form.value.id);
          getList();
        });
      } else {
        addScmSupplierOrders(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = true;
          orderFormDisabled.value = true; // 提交成功后恢复表单禁
          form.value = response.data;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除供应商订单编号为"' + row.orderCode + '"的数据项？').then(function() {
    return delScmSupplierOrders(_ids);
  }).then(() => {
    open.value = false;
    reset();
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 供应商订单明细序号 */
function rowScmSupplierOrderItemsIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}

/** 供应商订单明细添加按钮操作 */
function handleAddScmSupplierOrderItems() {
  let obj = {};
  obj.productId = "";
  obj.purchaseCategory = "";
  obj.demandType = "";
  obj.model = "";
  obj.manufactureNumber = "";
  obj.manufactureSubNumber = "";
  obj.drawingNumberModel = "";
  obj.drawingVersion = "";
  obj.productName = "";
  obj.material = "";
  obj.size = "";
  obj.specification = "";
  obj.color = "";
  obj.unitPriceType = "";
  obj.unitPrice = "";
  obj.quantity = "";
  obj.amount = "";
  obj.moldCost = "";
  obj.jigCost = "";
  obj.supplierCurrency = "";
  obj.supplierCurrencyRate = "";
  obj.requestedDeliveryDate = "";
  obj.repliedDeliveryDate = "";
  obj.remarks = "";
  scmSupplierOrderItemsList.value.push(obj);
}

/** 数量变化时自动计算金额 */
function handleQuantityChange(value, row) {
  if (row.unitPrice && value) {
    row.amount = (row.unitPrice * value).toFixed(2);
  } else {
    row.amount = 0;
  }
}
/** 单价变化时自动计算金额 */
function handleUnitPriceChange(value, row) {
  if (row.quantity && value) {
    row.amount = (row.quantity * value).toFixed(2);
  } else {
    row.amount = 0;
  }
}

/** 供应商订单明细删除按钮操作 */
function handleDeleteScmSupplierOrderItems() {
  if (checkedScmSupplierOrderItems.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的供应商订单明细数据");
  } else {
    const scmSupplierOrderItemss = scmSupplierOrderItemsList.value;
    const checkedScmSupplierOrderItemss = checkedScmSupplierOrderItems.value;
    scmSupplierOrderItemsList.value = scmSupplierOrderItemss.filter(function(item) {
      return checkedScmSupplierOrderItemss.indexOf(item.index) == -1
    });
  }
}

/** 复选框选中数据 */
function handleScmSupplierOrderItemsSelectionChange(selection) {
  checkedScmSupplierOrderItems.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('scm/scmSupplierOrders/export', {
    ...queryParams.value
  }, `scmSupplierOrders_${new Date().getTime()}.xlsx`)
}

getList();

/** 展示用户详情 */
function handleCurrentOrder(val){
  if (!val) return;
  open.value = true;
  form.value = val;
  orderFormDisabled.value = true; // 设置表单为禁用状态
// console.log(val.id);
//   reset();
  const _id = val.id
  inquiryCurrentOrder(_id);
}
/** 展示用户详情 */
function inquiryCurrentOrder(id){
  if (!id) return;
  getScmSupplierOrders(id).then(response => {
    form.value = response.data;
    scmSupplierOrderItemsList.value = response.data.scmSupplierOrderItemsList;
  });
}

// 列显隐信息
const columns = ref([
  { key: 0, label: `版本`, visible: true },
  { key: 1, label: `内版本`, visible: true },
  { key: 2, label: `品名`, visible: true },
  { key: 3, label: `材质`, visible: true },
  { key: 4, label: `规格`, visible: true },
  { key: 5, label: `颜色`, visible: true },
  { key: 6, label: `单台 用量`, visible: true },
  { key: 7, label: `月度 用量`, visible: true },
  { key: 8, label: `年度 用量`, visible: true },
  { key: 9, label: `一次性`, visible: true },
  { key: 10, label: `一次性试做`, visible: true },
  { key: 11, label: `试做`, visible: true },
  { key: 12, label: `量产`, visible: true },
  { key: 13, label: `希望报价日`, visible: true },
  { key: 14, label: `希望到货日`, visible: true },
  { key: 15, label: `需求资料`, visible: true },
  { key: 16, label: `备注`, visible: true }
]);

</script>

<style scoped>
.min-height {
  min-height: 300px !important;
}

.custom-divider {
  margin-top: 0px !important;    /* 调整上方距离 */
  margin-bottom: 15px !important;  /* 调整下方距离 */
}

/* 使用深度选择器确保 el-input-number 内容靠右对齐 */
:deep(.number-right .el-input__inner) {
  text-align: right !important;
}
</style>